<template>
  <div class="container">
    <Navbar></Navbar>
    <div class="captcha-box">
      <h2>请输入短信验证码</h2>
      <van-cell :border="false">
        <template #title>
          <span class="custom-title"> 验证码已发送至 {{mobile}}</span>
        </template>
        <template #right-icon>
          <van-button type="info" size="small" @click="send">{{text}}</van-button>
        </template>
      </van-cell>
      <van-field v-model="code" label="验证码" placeholder="请输入短信验证码" :border="false" />
      <div style="margin: 28px;">
        <van-button block native-type="submit" :color="code ? '#3ca7fa' : 'rgba(60,167,250,.6)'" @click="code && goToLogin()">登录/注册</van-button>
      </div>
    </div>
    <van-dialog v-model="show" show-cancel-button @confirm="reFetch">
      <template #default>
        <div style="display: flex;padding: 28px;">
          <van-field
            v-model="content"
            center
            placeholder="请输入图形验证码"
          >
          </van-field>
          <img v-lazy="captcha.img" style="width: 80px;height: 36px;" @click="change">
        </div>
      </template>
    </van-dialog>
  </div>
</template>

<script>
import Navbar from '@/components/common/Navbar';
import { smsLogin, getImageCode, getSms } from '@/network/member';
import { Notify } from 'vant';

export default {
  props: ['mobile'],
  components: {
    Navbar,
  },
  data() {
    return {
      code: '',
      time: 120,
      show: false,
      text: '',
      content: '',
      timer: null,
      captcha: {},
    };
  },
  methods: {
    init() {
      this.time = 120;
      this.text = `${this.time}s`;
      this.timer = setInterval(() => {
        this.time--;
        this.text = `${this.time}s`;
        if (this.time == 0) {
          this.text = '重新发送';
          clearInterval(this.timer);
        }
      }, 1000);
    },
    reFetch() {
      const userInfo = {
        mobile: this.mobile,
        image_captcha: this.content,
        image_key: this.captcha.key,
        scene: 'login',
      };
      getSms(userInfo);
    },
    change() {
      getImageCode().then((res) => {
        this.captcha = res.data;
      });
    },
    send() {
      if (this.text == '重新发送') {
        this.show = true;
      }
    },
    goToLogin() {
      smsLogin({ mobile: this.mobile, mobile_code: this.code }).then((res) => {
        Notify(res.message);
      });
    },
  },
  created() {
    this.init();
    this.change();
  },
};
</script>

<style lang="less" scoped>
h2 {
  font-size: 24px;
  font-weight: 400;
  margin: 28px 0 18px 28px;
}
.login {
  margin: 20px 0 40px;
  text-align: center;
  color: #3ca7fa;
}
.checkbox {
  color: rgba(0,0,0,.4);
  font-size: 12px;
  margin-left: 26px;
  a {
    font-size: 12px;
    color: #3ca7fa;
    margin: 0 8px;
  }
}
</style>
